<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>留言板增删(二次月考)</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        .box1 {
            width: 400px;
            margin: 100px auto;
        }

        input {
            width: 300px;
            height: 30px;
            margin-right: 20px;
        }

        button {
            cursor: pointer;
        }

        .box2 {
            margin-top: 20px;
        }

        ul {

            list-style-type: none;
        }

        li {
            left: auto;
            border-bottom: 1px dashed #030303;
            display: flex;
            justify-content: space-between;
        }

        li .a {
            color: red;
            cursor: pointer;
        }
    </style>
</head>

<body>
    <div class="box1">
        <div>
            <input type="text" id="name" autocomplete="off" placeholder="请输入内容">
            <button id="btn">发布</button>
        </div>

        <div class="box2">
            <ul id="list">
                <li>
                    你好
                    <span class="a">删除</span>
                </li>
            </ul>
        </div>

    </div>

    <script>
        let nameELe = document.getElementById('name');
        let btnELe = document.getElementById('btn');
        let listELe = document.getElementById('list');

        //点击发布按钮 
        btnELe.addEventListener('click', function () {

            // 获取输入的值
            let name = nameELe.value;
            // 给用户提示
            if (name == '') {
                return alert('你还没有输入内容')
            };

            //"ul">"li">"span",节点继承
            // 创建li节点
            let li = document.createElement('li');
            li.innerText = name;

            // 创建span节点，添加a类名
            let sapan = document.createElement("sapan")
            sapan.classList.add('a')
            sapan.innerText = '删除';
            console.log(sapan);

            // 获取span父节点,单击span标签删除父节点li
            sapan.addEventListener('click', function () {
                // parentNode获取父节点
                let parent = this.parentNode
                if (confirm('确认删除吗?')) {
                    parent.parentNode.removeChild(parent);
                }
            });

            // 将span类添加到父节点li里面
            li.appendChild(sapan);
            console.log(li);

            // 将li添加到ul里
            // 父元素.insertBefore(插入新节点,参考节点)
            listELe.insertBefore(li, listELe.firstChild)

            // 清空输入框的内容
            nameELe.value = '';
        });

    </script>


</body>

</html>